import { alertMessage } from '@/utils/utils';
import { getMenuTreeApi, getRolePermissionsApi, updateRolePermissionsApi } from './assign-permission.service';
export default {
  name: 'create-code',
  components: {},
  directives: {},
  props: {
    roleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false, // table loading
      showDialog: true, // 是否显示弹窗
      title: '分配菜单权限',
      treeData: [], // 菜单树
      data: [], // 操作码列表
      multipleSelection: [],
      defaultProps: {
        children: "children",
        label: "name"
      }
    }
  },
  created() {
    this.getMenuTree();
  },
  methods: {
    // 获取分配权限左侧菜单树状结果
    getMenuTree() {
      getMenuTreeApi().then(res => {
        this.treeData = res.data;
      });
    },

    // 获取选中的菜单树节点
    getSelectNode(event) {
      this.getPermissionCode(event.code)
    },

    // 获取操作码
    getPermissionCode(menuCode) {
      const params = {
        roleId: this.roleId,
        menuCode: menuCode,
        pageNum: 1,
        recordNum: 100
      }
      getRolePermissionsApi(params).then(res => {
        this.data = res.data;
        this.$nextTick(() => {
          this.multipleSelection = [];
          this.data.forEach(element => {
            if (element.checkFlag) {
              this.$refs.treeTable.toggleRowSelection(element);
              this.multipleSelection.push(element)
            }
          });
        })
      })
    },

    // 获取选中的code列表
    selectedCodes(selection) {
      this.multipleSelection = selection
    },

    // 创建或者编辑信息
    save() {
      // 遍历赋值checkflag,选中的赋值true,未选中赋值false
      this.data.forEach(element => {
        element.checkFlag = false
        this.multipleSelection.forEach(item => {
          if (element.objectId === item.objectId) {
            element.checkFlag = true
          }
        })
      })
      const dataChecks = this.data.map(v => ({ objectId: v.objectId, checkFlag: v.checkFlag }))
      const params = {
        roleId: this.roleId,
        dataChecks: dataChecks
      }
      updateRolePermissionsApi(params).then((res) => {
        alertMessage(res.message);
      }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
    },

    // 关闭dialog时需要告诉父组件隐藏弹窗
    closeDialog() {
      this.showDialog = false;
      this.$emit('close', true);
    }
  }
}